// Copyright (c) 2011 Blue Onion Software, All rights reserved
using System;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Web.UI.Design;
using System.Web.UI.WebControls;

namespace BlueOnionSoftware.Bloget
{
    [Designer(typeof (BlogetRecentPostsDesigner))]
    public class BlogetRecentPosts : Bloget
    {
        protected override void CreateChildControls()
        {
            RecentPosts();
            base.CreateChildControls();
        }

        private void RecentPosts()
        {
            if (IndexTemplate == null)
            {
                WriteLine(@"<ul class=""recentposts-list"">");
            }

            foreach (var post in Blog.EnumeratePosts(0, 10, QueryCategory, false, false))
            {
                if (post.Draft == false)
                {
                    if (IndexTemplate != null)
                    {
                        var indexContainer = new IndexContainerControl(this, Blog, post);
                        IndexTemplate.InstantiateIn(indexContainer);
                        Controls.Add(indexContainer);
                    }

                    else
                    {
                        Write("<li>");
                        var link = new HyperLink
                        {
                            Text = post.Title,
                            NavigateUrl = BuildQueryString(Mode.Post, post, 0, null, null, DateTime.MinValue, null)
                        };
                        Controls.Add(link);
                        WriteLine("</li>");
                    }
                }
            }

            if (IndexTemplate == null)
            {
                WriteLine("</ul>");
            }
        }
    }

    internal class BlogetRecentPostsDesigner : BlogetDesigner
    {
        public override string GetDesignTimeHtml()
        {
            return "<span>Sample Recent Post</span>";
        }

        [SuppressMessage("Microsoft.Security", "CA2116:AptcaMethodsShouldOnlyCallAptcaMethods")]
        public override TemplateGroupCollection TemplateGroups
        {
            get
            {
                var collection = new TemplateGroupCollection();
                var control = (Bloget) Component;
                var group = new TemplateGroup("Bloget");
                var template = new TemplateDefinition(this, "IndexTemplate", control, "IndexTemplate", true);
                group.AddTemplateDefinition(template);
                collection.Add(group);
                return collection;
            }
        }
    }
}